<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="定位器编码" prop="locatorCode">
        <el-input
          v-model="queryParams.locatorCode"
          placeholder="请输入定位器编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备型号" prop="deviceModel">
        <el-input
          v-model="queryParams.deviceModel"
          placeholder="请输入设备型号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="定位器状态" prop="locatorStatus">
        <el-select v-model="queryParams.locatorStatus" placeholder="请选择定位器状态" clearable>
          <el-option label="正常" value="1" />
          <el-option label="离线" value="2" />
          <el-option label="故障" value="3" />
          <el-option label="停用" value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="绑定状态" prop="bindStatus">
        <el-select v-model="queryParams.bindStatus" placeholder="请选择绑定状态" clearable>
          <el-option label="未绑定" value="unbound" />
          <el-option label="已绑定" value="bound" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['pack:locator:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['pack:locator:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pack:locator:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['pack:locator:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['pack:locator:import']"
        >导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="locatorList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column label="定位器编码" align="left" prop="locatorCode" width="140" :show-overflow-tooltip="true" />
      <el-table-column label="设备型号" align="left" prop="deviceModel" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="生产日期" align="center" prop="manufactureDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.manufactureDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="定位器状态" align="center" prop="locatorStatus" width="90">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.locatorStatus"
            active-value="1"
            inactive-value="4"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="绑定器具流水号" align="center" prop="boundContainer.containerCode" width="140">
        <template slot-scope="scope">
          <span v-if="scope.row.boundContainer">{{ scope.row.boundContainer.containerCode }}</span>
          <span v-else style="color: #999;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="器具类型编码" align="center" prop="boundContainer.materialCode" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.boundContainer">{{ scope.row.boundContainer.materialCode }}</span>
          <span v-else style="color: #999;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="最后在线时间" align="center" prop="lastOnlineTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastOnlineTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['pack:locator:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['pack:locator:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['pack:locator:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改定位器对话框 -->
    <el-drawer :title="title" :visible.sync="open" direction="rtl" size="67%" :before-close="cancel">
      <div style="padding: 20px;">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="定位器编码" prop="locatorCode">
                <el-input 
                  v-model="form.locatorCode" 
                  placeholder="请输入定位器编码" 
                  :disabled="form.locatorId != null"
                  @blur="checkLocatorCodeUnique"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备型号" prop="deviceModel">
                <el-input v-model="form.deviceModel" placeholder="请输入设备型号" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="生产日期" prop="manufactureDate">
                <el-date-picker
                  v-model="form.manufactureDate"
                  type="date"
                  placeholder="选择生产日期"
                  value-format="yyyy-MM-dd"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="定位器状态" prop="locatorStatus">
                <el-select v-model="form.locatorStatus" placeholder="请选择定位器状态" style="width: 100%">
                  <el-option label="正常" value="1" />
                  <el-option label="离线" value="2" />
                  <el-option label="故障" value="3" />
                  <el-option label="停用" value="4" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="对应器具" prop="containerId">
                <el-select
                  v-model="form.containerId"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入器具编码或器具流水号搜索"
                  :remote-method="remoteSearchContainers"
                  :loading="containerLoading"
                  style="width: 100%"
                  clearable
                >
                  <el-option
                    v-for="item in containerOptions"
                    :key="item.containerId"
                    :label="item.containerCode + ' - ' + item.materialName"
                    :value="item.containerId"
                  >
                    <span>{{ item.containerCode }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ item.materialCode }} - {{ item.materialName }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="备注">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="drawer-footer">
          <el-button size="mini" @click="cancel">取 消</el-button>
          <el-button size="mini" type="primary" @click="submitForm">确 定</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 定位器详情对话框 -->
    <el-drawer title="定位器详情" :visible.sync="detailOpen" direction="rtl" size="67%">
      <div style="padding: 20px;">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="定位器编码">{{ detailData.locatorCode }}</el-descriptions-item>
          <el-descriptions-item label="设备型号">{{ detailData.deviceModel || '-' }}</el-descriptions-item>
          <el-descriptions-item label="生产日期">{{ parseTime(detailData.manufactureDate, '{y}-{m}-{d}') || '-' }}</el-descriptions-item>
          <el-descriptions-item label="定位器状态">
            <el-tag v-if="detailData.locatorStatus === '1'" type="success">正常</el-tag>
            <el-tag v-else-if="detailData.locatorStatus === '2'" type="warning">离线</el-tag>
            <el-tag v-else-if="detailData.locatorStatus === '3'" type="danger">故障</el-tag>
            <el-tag v-else-if="detailData.locatorStatus === '4'" type="info">停用</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="绑定状态">
            <el-tag v-if="detailData.bindStatus === 'bound'" type="success">已绑定</el-tag>
            <el-tag v-else type="info">未绑定</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="绑定器具">
            <span v-if="detailData.boundContainer">{{ detailData.boundContainer.containerCode }} - {{ detailData.boundContainer.materialName }}</span>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="最后在线时间">{{ parseTime(detailData.lastOnlineTime, '{y}-{m}-{d} {h}:{i}:{s}') || '-' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">{{ parseTime(detailData.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
          <el-descriptions-item label="更新时间" :span="2">{{ parseTime(detailData.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ detailData.remark || '-' }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-drawer>

    <!-- 定位器导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          <div class="el-upload__tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的定位器数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { 
  listLocator, 
  getLocator, 
  delLocator, 
  addLocator, 
  updateLocator, 
  updateLocatorStatus,
  checkLocatorCode,
  exportLocator,
  importTemplate
} from "@/api/pack/locator";
import { listContainerForLocator } from "@/api/pack/container";

export default {
  name: "Locator",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 定位器表格数据
      locatorList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      detailOpen: false,
      // 详情数据
      detailData: {},
      // 文件上传参数
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的定位器数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + this.$store.getters.token },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/pack/locator/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        locatorCode: null,
        deviceModel: null,
        locatorStatus: null,
        bindStatus: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        locatorCode: [
          { required: true, message: "定位器编码不能为空", trigger: "blur" },
          { min: 1, max: 50, message: "定位器编码长度必须介于 1 和 50 之间", trigger: "blur" }
        ],
        locatorStatus: [
          { required: true, message: "定位器状态不能为空", trigger: "change" }
        ]
      },
      // 器具选项
      containerOptions: [],
      // 器具搜索加载状态
      containerLoading: false
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询定位器列表 */
    getList() {
      this.loading = true;
      listLocator(this.queryParams).then(response => {
        this.locatorList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        locatorId: null,
        locatorCode: null,
        deviceModel: null,
        manufactureDate: null,
        locatorStatus: "1",
        containerId: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.locatorId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加定位器";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const locatorId = row.locatorId || this.ids;
      getLocator(locatorId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改定位器";
      });
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      const locatorId = row.locatorId;
      getLocator(locatorId).then(response => {
        this.detailData = response.data;
        this.detailOpen = true;
      });
    },
    /** 状态修改 */
    handleStatusChange(row) {
      let text = row.locatorStatus === "1" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.locatorCode + '"定位器吗？').then(function() {
        return updateLocatorStatus(row.locatorId, row.locatorStatus);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.locatorStatus = row.locatorStatus === "1" ? "4" : "1";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.locatorId != null) {
            updateLocator(this.form.locatorId, this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLocator(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const locatorIds = row.locatorId || this.ids;
      this.$modal.confirm('是否确认删除定位器编码为"' + (row.locatorCode || this.locatorList.filter(item => this.ids.indexOf(item.locatorId) !== -1).map(item => item.locatorCode).join('", "')) + '"的数据项？').then(function() {
        return delLocator(locatorIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('pack/locator/export', {
        ...this.queryParams
      }, `locator_${new Date().getTime()}.xlsx`)
    },
    /** 校验定位器编码唯一性 */
    checkLocatorCodeUnique() {
      if (this.form.locatorCode && this.form.locatorCode.trim() !== '') {
        checkLocatorCode(this.form.locatorCode).then(response => {
          if (!response.data) {
            this.$modal.msgError("定位器编码已存在，请修改后重试");
            this.$refs.form.validateField('locatorCode');
          }
        });
      }
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "定位器导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('/pack/locator/importTemplate', {}, `locator_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 远程搜索器具 */
    remoteSearchContainers(query) {
      if (query !== '') {
        this.containerLoading = true;
        this.containerOptions = []; // 清空选项
        
        console.log('搜索器具:', query);
        
        // 简化搜索逻辑，只按器具编码搜索
        listContainerForLocator({
          pageNum: 1,
          pageSize: 10,
          containerCode: query
        }).then(response => {
          console.log('API响应:', response);
          this.containerOptions = response.rows || [];
        }).catch(error => {
          console.error('搜索器具失败:', error);
          this.containerOptions = [];
        }).finally(() => {
          this.containerLoading = false;
        });
      } else {
        this.containerOptions = [];
      }
    }
  }
};
</script>

<style scoped>
.drawer-footer {
  text-align: center;
  margin-top: 20px;
}
</style> 